package cn.jjxx.modules.portal.controller;

import cn.jjxx.core.common.controller.BaseController;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.utils.CacheUtils;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.modules.portal.dto.UserDto;
import cn.jjxx.modules.portal.service.IRegisterService;
import cn.jjxx.modules.sys.entity.User;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 用户注册Controller
 * @author mali
 * @date 2019-01-16
 */
@Controller
@RequestMapping("/portal/register")
public class RegisterController extends BaseController {

    @Autowired
    private IRegisterService registerService;

    /**
     * 注册时获取短信验证码
     * @param request request
     * @param phone phone
     * @return json
     * @author mali
     * @date 2019-01-16
     */
    @RequestMapping(value = "getSMSCodeByReg")
    @ResponseBody
    public AjaxJson getSMSCodeByReg(HttpServletRequest request, String phone) {
        return registerService.getSMSCodeByReg(request, phone);
    }

    /**
     * 注册接口
     * 用户类型只能是individual|company
     * @param request req
     * @param userDto userDto
     * @param bindingResult bindingResult
     * @return json
     * @author mali
     * @date 2019-01-16
     */
    @RequestMapping(value = "register")
    @ResponseBody
    public AjaxJson register(HttpServletRequest request, @Valid UserDto userDto, BindingResult bindingResult) {
        String errorMsg = errorMsg(bindingResult);
        if (StringUtils.isNotBlank(errorMsg)) {
            AjaxJson ajaxJson = new AjaxJson();
            ajaxJson.fail(errorMsg);
            return ajaxJson;
        }
        return registerService.register(request, userDto);
    }

    private String errorMsg(BindingResult result) {
        String errorMsg = "";
        if (result.getErrorCount() > 0) {
            List<ObjectError> objectErrorList = result.getAllErrors();
            for (ObjectError objectError : objectErrorList) {
                String message = MessageUtils.getMessage(objectError.getCode(), objectError.getDefaultMessage(),
                        objectError.getArguments());
                if (!StringUtils.isEmpty(message)) {
                    errorMsg = errorMsg + message + "<br />";
                }
            }
        }
        return errorMsg;
    }
}
